package org.light.verb;

import java.util.ArrayList;
import java.util.List;

import org.light.core.Verb;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.StatementList;
import org.light.domain.Type;
import org.light.domain.Var;
import org.light.easyui.EasyUIPositions;
import org.light.exception.ValidateException;
import org.light.generator.NamedS2SMStatementGenerator;
import org.light.generator.NamedS2SMStatementListGenerator;
import org.light.generator.NamedStatementGenerator;
import org.light.generator.NamedStatementListGenerator;
import org.light.utils.InterVarUtil;
import org.light.utils.StringUtil;
import org.light.utils.WriteableUtil;

public class Clone extends Verb implements EasyUIPositions {

	@Override
	public Method generateDaoImplMethod() throws Exception{
		return null;
	}

	@Override
	public Method generateDaoMethodDefinition() throws Exception{
		return null;
	}

	@Override
	public Method generateServiceMethodDefinition() throws Exception{
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("clone"+StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(new Type("boolean"));
			method.setThrowException(true);
			method.addAdditionalImport("java.util.List");
			method.addAdditionalImport(this.domain.getPackageToken()+ "."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			method.addSignature(new Signature(1,this.domain.getDomainId().getFieldName(),this.domain.getDomainId().getClassType()));
			return method;
		}
	}

	@Override
	public Method generateServiceImplMethod() throws Exception{
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("clone"+StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(new Type("boolean"));
			method.setThrowException(true);
			method.addAdditionalImport("java.util.List");
			method.addAdditionalImport(this.domain.getPackageToken()+ ".utils.StringUtil");
			method.addAdditionalImport(this.domain.getPackageToken()+ "."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDaoSuffix()+"."+this.domain.getStandardName()+"Dao");
			method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getServiceSuffix()+"."+this.domain.getStandardName()+"Service");
			method.addSignature(new Signature(1,this.domain.getDomainId().getLowerFirstFieldName(),this.domain.getDomainId().getClassType()));
			method.addMetaData("Override");
			
			FindFullInfoById find = new FindFullInfoById(this.domain);
			SearchIndexedNamesByShortName search = new SearchIndexedNamesByShortName(this.domain);
					
			List<Writeable> sList = new ArrayList<Writeable>();
			sList.add(NamedStatementGenerator.getDBConfInitDBAutoRelease(500L, 2, InterVarUtil.DB.connection, InterVarUtil.DB.dbconf));
			sList.add(new Statement(1000L,3,""+this.domain.getCapFirstDomainNameWithSuffix()+" "+this.domain.getLowerFirstDomainName()+" = dao."+StringUtil.lowerFirst(find.getVerbName())+"(connection,"+this.domain.getDomainId().getLowerFirstFieldName()+");"));
			sList.add(new Statement(2000L,3,""));
			sList.add(new Statement(3000L,3,"String "+this.domain.getDomainName().getLowerFirstFieldName()+" = "+this.domain.getLowerFirstDomainName()+".get"+this.domain.getDomainName().getCapFirstFieldName()+"();"));
			sList.add(new Statement(4000L,3,"String shortName = "+this.domain.getDomainName().getLowerFirstFieldName()+";"));
			sList.add(new Statement(5000L,3,"if ("+this.domain.getDomainName().getLowerFirstFieldName()+".contains(\"_\") && StringUtil.isInteger("+this.domain.getDomainName().getLowerFirstFieldName()+".substring("+this.domain.getDomainName().getLowerFirstFieldName()+".lastIndexOf('_')+1,"+this.domain.getDomainName().getLowerFirstFieldName()+".length()))) {"));
			sList.add(new Statement(6000L,3,"shortName = "+this.domain.getDomainName().getLowerFirstFieldName()+".substring(0,"+this.domain.getDomainName().getLowerFirstFieldName()+".lastIndexOf('_'));"));
			sList.add(new Statement(7000L,3,"}"));
			sList.add(new Statement(8000L,3,"List<"+this.domain.getCapFirstDomainNameWithSuffix()+"> names = dao."+StringUtil.lowerFirst(search.getVerbName())+"(connection, shortName);"));
			sList.add(new Statement(9000L,3,"int indexNum = 1;"));
			sList.add(new Statement(10000L,3,"for ("+this.domain.getCapFirstDomainNameWithSuffix()+" "+this.domain.getLowerFirstDomainName()+"0:names) {"));
			sList.add(new Statement(11000L,4,"String _name = "+this.domain.getLowerFirstDomainName()+"0.get"+this.domain.getDomainName().getCapFirstFieldName()+"();"));
			sList.add(new Statement(12000L,4,"if (_name.contains(\"_\") && StringUtil.isInteger(_name.substring(_name.lastIndexOf('_')+1,_name.length()))) {"));
			sList.add(new Statement(14000L,5,"int index = Integer.valueOf(_name.substring(_name.lastIndexOf('_')+1,_name.length()));"));
			sList.add(new Statement(15000L,5,"if (index >= indexNum) {"));
			sList.add(new Statement(16000L,6,"indexNum = index + 1;"));
			sList.add(new Statement(17000L,5,"}"));
			sList.add(new Statement(18000L,4,"}"));
			sList.add(new Statement(19000L,3,"}"));
			sList.add(new Statement(20000L,3,"String indexName = shortName + \"_\" + indexNum;"));
			sList.add(new Statement(20500L,3, this.domain.getCapFirstDomainNameWithSuffix()+" "+this.domain.getLowerFirstDomainName()+"1 = "+this.domain.getLowerFirstDomainName()+".clone();"));
			sList.add(new Statement(21000L,3,""+this.domain.getLowerFirstDomainName()+"1.set"+this.domain.getDomainName().getCapFirstFieldName()+"(indexName);"));
			sList.add(new Statement(22000L,3,"dao.add"+this.domain.getCapFirstDomainName()+"(connection,"+this.domain.getLowerFirstDomainName()+"1);"));
			sList.add(new Statement(23000L,3,"return true;"));
			sList.add(NamedStatementGenerator.getLoopFooter(24000L, 2));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}

	public Clone(){
		super();
		this.setLabel("克隆");
	}
	
	public Clone(Domain domain) throws ValidateException{
		super();
		this.domain = domain;
		this.denied = domain.isVerbDenied("Clone");
		this.setVerbName("Clone"+StringUtil.capFirst(this.domain.getStandardName()));
		this.setLabel("克隆");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("Clone");
	}

	@Override
	public Method generateControllerMethod() throws Exception{
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("processRequest");
			method.setReturnType(new Type("void"));
			method.setThrowException(true);
			List<String> list = new ArrayList<String>();
			list.add("ServletException");
			list.add("IOException");
			method.setIsprotected(true);
			method.setOtherExceptions(list);
			method.addSignature(new Signature(1,"request",new Type("HttpServletRequest","javax.servlet.http")));
			method.addSignature(new Signature(2,"response",new Type("HttpServletResponse","javax.servlet.http")));
			method.addAdditionalImport("java.io.IOException");
			method.addAdditionalImport("java.io.PrintWriter");
			method.addAdditionalImport("javax.servlet.ServletException");
			method.addAdditionalImport("javax.servlet.http.HttpServlet");
			method.addAdditionalImport("javax.servlet.http.HttpServletRequest");
			method.addAdditionalImport("javax.servlet.http.HttpServletResponse");
			method.addAdditionalImport("java.util.Map");
			method.addAdditionalImport("java.util.TreeMap");
			method.addAdditionalImport("net.sf.json.JSONObject");
			method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getServiceSuffix()+"."+this.domain.getStandardName()+"Service");
			method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getServiceimplSuffix()+"."+this.domain.getStandardName()+"ServiceImpl");
	
			List<Writeable> wlist = new ArrayList<Writeable>();
			Var service = new Var("service", new Type(this.domain.getStandardName()+"Service",this.domain.getPackageToken()));
			Var resultMap = new Var("result", new Type("TreeMap<String,Object>","java.util"));
			wlist.add(NamedStatementGenerator.getFacadeSetContentType(1000L, 2, InterVarUtil.Servlet.response, InterVarUtil.SimpleJEE.UTF8.getVarName()));
			wlist.add(NamedStatementGenerator.getControllerPrintWriterOut(2000L, 2, InterVarUtil.Servlet.response, InterVarUtil.Servlet.out));
			wlist.add(NamedStatementGenerator.getJsonResultMap(3000L, 2, resultMap));
			wlist.add(NamedStatementGenerator.getTryHead(4000L, 2));
			//wlist.add(NamedStatementGenerator.getPrepareDomainVarInit(5000L, 2, this.domain));
			wlist.add(NamedStatementGenerator.getSetDomainIdFromRequest(6000L, 3, this.domain, InterVarUtil.Servlet.request));
			wlist.add(NamedStatementGenerator.getPrepareService(7000L,3, service));
			wlist.add(NamedStatementGenerator.getCallServiceMethodAssignSuccess(8000L, 3, service, generateServiceMethodDefinition()));
			wlist.add(NamedStatementListGenerator.getPutJsonResultMapWithSuccessAssignAndNull(9000L, 3, resultMap));
			wlist.add(NamedStatementGenerator.getEncodeMapToJsonResultMap(10000L, 3, resultMap,InterVarUtil.Servlet.out));
		wlist.add(NamedStatementListGenerator.generateCatchExceptionPrintStackPrintJsonMapFinallyCloseOutFooter(11000L, 2, InterVarUtil.Servlet.response,resultMap, InterVarUtil.Servlet.out));	
			method.setMethodStatementList(WriteableUtil.merge(wlist));
			
			return method;
		}
	}

	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		if (this.denied) return null;
		else {
			JavascriptBlock block = new JavascriptBlock();
			block.setSerial(100);
			block.setStandardName("clone"+domain.getCapFirstDomainName());
			StatementList sl = new StatementList();
			sl.add(new Statement(1000,0, "{"));
			if (this.domain.getLanguage().equalsIgnoreCase("english")) {
				sl.add(new Statement(2000, 1, "text:'Clone',"));
			}else {
				sl.add(new Statement(2000,1, "text:'克隆',"));
			}
			sl.add(new Statement(3000,1, "iconCls:'icon-add',"));
			sl.add(new Statement(4000,1, "handler:function(){ "));
			sl.add(new Statement(5000,2, "var rows = $(\"#dg\").datagrid(\"getChecked\");"));
			sl.add(new Statement(6000,2, "if (rows == undefined || rows == null || rows.length == 0 ){"));
			if (this.domain.getLanguage().equalsIgnoreCase("english")) {
				sl.add(new Statement(7000,3, "$.messager.alert(\"Alert\",\"Please choose one record!\",\"warning\");"));
			}else {
				sl.add(new Statement(7000,3,"$.messager.alert(\"警告\",\"请选定一条记录！\",\"warning\");"));
			}
			sl.add(new Statement(8000,3, "return;"));
			sl.add(new Statement(9000,2, "}"));
			sl.add(new Statement(10000,2, "if (rows.length > 1) {"));
			if (this.domain.getLanguage().equalsIgnoreCase("english")) {
				sl.add(new Statement(11000,3, "$.messager.alert(\"Alert\",\"Please choose one record!\",\"warning\");"));
			}else {
				sl.add(new Statement(11000,3, "$.messager.alert(\"警告\",\"请选定一条记录！\",\"warning\");"));
			}
			sl.add(new Statement(12000,3, "return;"));
			sl.add(new Statement(13000,2, "}"));
			sl.add(new Statement(14000,2, "var "+domain.getDomainId().getLowerFirstFieldName()+" = rows[0][\""+domain.getDomainId().getLowerFirstFieldName()+"\"];"));
			sl.add(new Statement(15000,2, "clone"+this.domain.getCapFirstDomainName()+"("+domain.getDomainId().getLowerFirstFieldName()+");"));
			sl.add(new Statement(16000,1, "}"));
			sl.add(new Statement(17000,0, "}"));
			block.setMethodStatementList(sl);
			return block;
		}
	}

	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		if (this.denied) return null;
		else {
			Domain domain = this.domain;
			Var id = new Var(domain.getDomainId().getLowerFirstFieldName(),new Type("var"));
			JavascriptMethod method = new JavascriptMethod();
			method.setSerial(200);
			method.setStandardName("clone"+domain.getCapFirstDomainName());
			Signature s1 = new Signature();
			s1.setName(id.getVarName());
			s1.setPosition(1);
			s1.setType(new Type("var"));	
			method.addSignature(s1);
			
			StatementList sl = new StatementList();
			sl.add(new Statement(1000,1, "$.ajax({"));
			sl.add(new Statement(2000,2, "type: \"post\","));
			sl.add(new Statement(3000,2, "url: \"../"+domain.getControllerPackagePrefix()+domain.getLowerFirstDomainName()+domain.getControllerNamingSuffix()+"/"+StringUtil.lowerFirst(this.getVerbName())+"\","));
			sl.add(new Statement(4000,2, "data: {"));
			sl.add(new Statement(5000,3, "\""+domain.getDomainId().getLowerFirstFieldName()+"\":"+domain.getDomainId().getLowerFirstFieldName()+"	"));	
			sl.add(new Statement(6000,2, "},"));
			sl.add(new Statement(7000,2, "dataType: 'json',"));
			sl.add(new Statement(8000,2, "success: function(data, textStatus) {"));
			sl.add(new Statement(9000,3, "$(\"#dg\").datagrid(\"load\");"));
			sl.add(new Statement(10000,2, "},"));
			sl.add(new Statement(11000,2, "complete : function(XMLHttpRequest, textStatus) {"));
			sl.add(new Statement(12000,2, "},"));
			sl.add(new Statement(13000,2, "error : function(XMLHttpRequest,textStatus,errorThrown) {"));
			sl.add(new Statement(14000,3, "alert(\"Error:\"+textStatus);"));
			sl.add(new Statement(15000,3, "alert(errorThrown.toString());"));
			sl.add(new Statement(16000,2, "}"));
			sl.add(new Statement(17000,1, "});"));
			
			method.setMethodStatementList(sl);
			return method;	
		}
	}
	
	@Override
	public Method generateDummyDaoImplMethod() throws Exception {
		return null;
	}

	@Override
	public Method generateDummyServiceImplMethod() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("clone"+StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(new Type("boolean"));
			method.setThrowException(true);
			method.addAdditionalImport("java.util.List");
			method.addAdditionalImport(this.domain.getPackageToken()+ ".utils.StringUtil");
			method.addAdditionalImport(this.domain.getPackageToken()+ "."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDaoSuffix()+"."+this.domain.getStandardName()+"Dao");
			method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getServiceSuffix()+"."+this.domain.getStandardName()+"Service");
			method.addSignature(new Signature(1,this.domain.getDomainId().getLowerFirstFieldName(),this.domain.getDomainId().getClassType()));
			method.addMetaData("Override");
			
			FindFullInfoById find = new FindFullInfoById(this.domain);
			SearchIndexedNamesByShortName search = new SearchIndexedNamesByShortName(this.domain);
					
			List<Writeable> sList = new ArrayList<Writeable>();
			sList.add(new Statement(1000L,2,""+this.domain.getCapFirstDomainNameWithSuffix()+" "+this.domain.getLowerFirstDomainName()+" = dao."+StringUtil.lowerFirst(find.getVerbName())+"("+this.domain.getDomainId().getLowerFirstFieldName()+");"));
			sList.add(new Statement(2000L,2,""));
			sList.add(new Statement(3000L,2,"String "+this.domain.getDomainName().getLowerFirstFieldName()+" = "+this.domain.getLowerFirstDomainName()+".get"+this.domain.getDomainName().getCapFirstFieldName()+"();"));
			sList.add(new Statement(4000L,2,"String shortName = "+this.domain.getDomainName().getLowerFirstFieldName()+";"));
			sList.add(new Statement(5000L,2,"if ("+this.domain.getDomainName().getLowerFirstFieldName()+".contains(\"_\") && StringUtil.isInteger("+this.domain.getDomainName().getLowerFirstFieldName()+".substring("+this.domain.getDomainName().getLowerFirstFieldName()+".lastIndexOf('_')+1,"+this.domain.getDomainName().getLowerFirstFieldName()+".length()))) {"));
			sList.add(new Statement(6000L,2,"shortName = "+this.domain.getDomainName().getLowerFirstFieldName()+".substring(0,"+this.domain.getDomainName().getLowerFirstFieldName()+".lastIndexOf('_'));"));
			sList.add(new Statement(7000L,2,"}"));
			sList.add(new Statement(8000L,2,"List<"+this.domain.getCapFirstDomainNameWithSuffix()+"> names = dao."+StringUtil.lowerFirst(search.getVerbName())+"(shortName);"));
			sList.add(new Statement(9000L,2,"int indexNum = 1;"));
			sList.add(new Statement(10000L,2,"for ("+this.domain.getCapFirstDomainNameWithSuffix()+" "+this.domain.getLowerFirstDomainName()+"0:names) {"));
			sList.add(new Statement(11000L,3,"String _name = "+this.domain.getLowerFirstDomainName()+"0.get"+this.domain.getDomainName().getCapFirstFieldName()+"();"));
			sList.add(new Statement(12000L,3,"if (_name.contains(\"_\") && StringUtil.isInteger(_name.substring(_name.lastIndexOf('_')+1,_name.length()))) {"));
			sList.add(new Statement(14000L,4,"int index = Integer.valueOf(_name.substring(_name.lastIndexOf('_')+1,_name.length()));"));
			sList.add(new Statement(15000L,4,"if (index >= indexNum) {"));
			sList.add(new Statement(16000L,5,"indexNum = index + 1;"));
			sList.add(new Statement(17000L,4,"}"));
			sList.add(new Statement(18000L,3,"}"));
			sList.add(new Statement(19000L,2,"}"));
			sList.add(new Statement(20000L,2,"String indexName = shortName + \"_\" + indexNum;"));
			sList.add(new Statement(20500L,2, this.domain.getCapFirstDomainNameWithSuffix()+" "+this.domain.getLowerFirstDomainName()+"1 = "+this.domain.getLowerFirstDomainName()+".clone();"));
			sList.add(new Statement(21000L,2,""+this.domain.getLowerFirstDomainName()+"1.set"+this.domain.getDomainName().getCapFirstFieldName()+"(indexName);"));
			sList.add(new Statement(22000L,2,"dao.add"+this.domain.getCapFirstDomainName()+"("+this.domain.getLowerFirstDomainName()+"1);"));
			sList.add(new Statement(23000L,2,"return true;"));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}

	@Override
	public Method generateDummyDaoMethodDefinition() throws Exception {
		return null;
	}
}
